//
//  QZMyOrderDetailVc.m
//  WeiWeiHaircut
//
//  Created by 上官惠阳 on 15/12/10.
//  Copyright © 2015年 超群. All rights reserved.
//

#import "QZMyOrderDetailVc.h"
#import "OrderDetailNumCell.h"
#import "OrderDetailCommomTableViewCell.h"
#import "OrderDetailImageCell.h"
#import "PayMoneyViewController.h"
#import "QZBottomView.h"
#import "QZRefundOrderBottomView.h"
#import "QZAddressController.h"
#import "QZAddressModel.h"
#import "QZTowLabelCell.h"
#import "QZOrderModel.h"
#import "QZAddressModel.h"
#import "ShaoppingCarViewController.h"
#import "MyOrdersViewController.h"
@interface QZMyOrderDetailVc ()
@property (nonatomic, strong) QZOrderModel *orderModel;
@end

@implementation QZMyOrderDetailVc
{
    QZBottomView *_bottomView;
    QZRefundOrderBottomView *_refundBottomView;
    UIButton *_cancleOrderBtn;
    QZTowLabelCell *_orderNoView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self titleWithSting:@"订单详情"];
    
    [self addBtnOnNavWithTitle:@"订单" andImageName:@"返回" andTarget:self andAction:@selector(backAction) andFrame:CGRectMake(0, 0, 45, 20) andDirection:left];
    
    [self createTableViewWithPlainStyle:NO andSeparatorStyleNone:YES andBackGroudImageName:nil];
    self.tableView.frame = CGRectMake(0, 0, WIDTH, HEIGHT-64);
    [self registCellWithNib:@"OrderDetailNumCell" addIdentifier:@"OrderDetailNumCell" addHeight:0];
    [self registCellWithNib:@"OrderDetailCommomTableViewCell" addIdentifier:@"OrderDetailCommomTableViewCell" addHeight:0];
    [self registCellWithNib:@"OrderDetailImageCell" addIdentifier:@"OrderDetailImageCell" addHeight:0];
    
    [self createBottomView:self.tmpOrder.orderStatus];
    
    [self loadData];
    
    [self downloadDatas];
}
-(void)downloadDatas{
    
    NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"ProdOrder.GetProdOrderInfo"];

    NSDictionary *dic = @{@"order_id":@(self.tmpOrder.id)};
    
    [self.request QZRequest_POST:url parameters:dic tagNSString:@"获取订单详情" stopRequest:YES isSerializer:NO isCache:YES];

    
}
-(void)loadData
{

    
    _orderNoView = [[[NSBundle mainBundle] loadNibNamed:@"QZTowLabelCell" owner:nil options:nil] lastObject];
    _orderNoView.frame = CGRectMake(0, 0, WIDTH, 30);
    self.tableView.tableHeaderView = _orderNoView;
    
    [self.tableView reloadData];
}
-(void)createBottomView:(NSInteger)index
{

    if (index == 0) {//未付款
        
        if (_cancleOrderBtn) {
            return;
        }
        _cancleOrderBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancleOrderBtn.frame = CGRectMake(0, HEIGHT - 49 - 40 - 64, WIDTH, 40);
        [_cancleOrderBtn setTitle:@"取消订单" forState:UIControlStateNormal];
        [_cancleOrderBtn addTarget:self action:@selector(cancleAction) forControlEvents:UIControlEventTouchUpInside];
        [_cancleOrderBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        _cancleOrderBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        [self.view addSubview:_cancleOrderBtn];
        
        _bottomView = [[[NSBundle mainBundle] loadNibNamed:@"QZBottomView" owner:self options:nil]lastObject];
        _bottomView.frame = CGRectMake(0, HEIGHT - 49 - 64, WIDTH, 49);
        [_bottomView.bottomBtn setTitle:@"立即支付" forState:UIControlStateNormal];
        [_bottomView.bottomBtn addTarget:self action:@selector(payAction) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:_bottomView];
    }else{
        
        if (!_refundBottomView) {
            _refundBottomView = [[[NSBundle mainBundle]loadNibNamed:@"QZRefundOrderBottomView" owner:self options:nil]lastObject];
            _refundBottomView.frame = CGRectMake(0, HEIGHT - 49 - 64, WIDTH, 49);
        }

        if (index == 1) {//待发货
            _refundBottomView.consigBtn.hidden = YES;
            _refundBottomView.afterSalesBtn.hidden = YES;
            _refundBottomView.logisticsBtn.hidden = YES;
            
        }else if (index == 2){//待收款
            _refundBottomView.afterSalesBtn.hidden = YES;
            
        }else if (index == 5){//交易完成
            
            _refundBottomView.consigBtn.hidden = YES;
            _refundBottomView.logisticsBtn.hidden = YES;
            _refundBottomView.refundBtn.hidden = YES;
            
        }else if (index == 3){//退款中
//            _refundBottomView.consigBtn.hidden = YES;
//            _refundBottomView.afterSalesBtn.hidden = YES;
//            _refundBottomView.logisticsBtn.hidden = YES;
//            _refundBottomView.refundBtn.hidden = YES;
                _refundBottomView.hidden = YES;
            _bottomView.hidden = YES;
        }else if (index == 4){//已退款
//            _refundBottomView.consigBtn.hidden = YES;
//            _refundBottomView.afterSalesBtn.hidden = YES;
//            _refundBottomView.logisticsBtn.hidden = YES;
//            _refundBottomView.refundBtn.hidden = YES;
           _refundBottomView.hidden = YES;
        }else if (index == -1){//已取消
//            _refundBottomView.consigBtn.hidden = YES;
//            _refundBottomView.afterSalesBtn.hidden = YES;
//            _refundBottomView.logisticsBtn.hidden = YES;
//            _refundBottomView.refundBtn.hidden = YES;
            _refundBottomView.hidden = YES;
        }
        
        [_refundBottomView.refundBtn addTarget:self action:@selector(refundAction) forControlEvents:UIControlEventTouchUpInside];
        [_refundBottomView.logisticsBtn addTarget:self action:@selector(logisticsAction) forControlEvents:UIControlEventTouchUpInside];
        [_refundBottomView.consigBtn addTarget:self action:@selector(consigAction) forControlEvents:UIControlEventTouchUpInside];
        [_refundBottomView.afterSalesBtn addTarget:self action:@selector(afterSalesAction) forControlEvents:UIControlEventTouchUpInside];
        
        [self.view addSubview:_refundBottomView];
    }
}
//取消订单
-(void)cancleAction
{
    NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"ProdOrder.GetProdOrderCancel"];
    
    NSDictionary *dic = @{
                          @"order_id":@(self.tmpOrder.id),
                          @"user_id":[QZUserInfo userId]
                          };
    [self.request QZRequest_POST:url parameters:dic tagNSString:@"取消预约" stopRequest:YES isSerializer:NO isCache:NO];
}
//立即支付
-(void)payAction
{
    PayMoneyViewController  * payVC = [[PayMoneyViewController alloc]initWithNibName:nil bundle:nil];
    payVC.model = self.orderModel;
    payVC.payOrderMoney = YES;
    payVC.isAppointment = NO;
    [self.navigationController pushViewController:payVC animated:YES];
}
//查看物流
-(void)logisticsAction
{
    
}
//确认收货
-(void)consigAction
{
    NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"ProdOrder.GetProdeOrderAffirm"];
    
    NSDictionary *dic = @{
                          @"order_id":@(self.tmpOrder.id),
                          @"user_id":[QZUserInfo userId]
                          };
    [self.request QZRequest_POST:url parameters:dic tagNSString:@"确认收货" stopRequest:YES isSerializer:NO isCache:NO];
}
//退款
-(void)refundAction
{
    NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"ProdOrder.GetProdeOrderRefund"];
    
    [self.request QZRequest_POST:url parameters:@{@"order_id":@(self.orderModel.id),@"user_id":[QZUserInfo userId]} tagNSString:@"退款" stopRequest:NO isSerializer:NO isCache:NO];
    
}
//申请售后
-(void)afterSalesAction
{
    NSString *url = [NSString stringWithFormat:@"%@%@",newPublicURL,@"ProdOrder.GetProdeOrderService"];
    
    NSDictionary *dic = @{
                          @"order_id":@(self.tmpOrder.id),
                          @"user_id":[QZUserInfo userId]
                          };
    [self.request QZRequest_POST:url parameters:dic tagNSString:@"售后" stopRequest:YES isSerializer:NO isCache:NO];

}
-(void)backAction
{
    if (_isPayView) {
        for (UIViewController *controll in self.navigationController.childViewControllers) {
            if ([controll class] == [ShaoppingCarViewController class]|| [controll class] == [MyOrdersViewController class]) {
                
                [self.navigationController popToViewController:controll animated:YES];
            }
        }
        return;
    }
    
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - tableheaderView
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.00000001;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView* headerTitleView     = [[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 40)];
    [headerTitleView setBackgroundColor:[UIColor whiteColor]];
    headerTitleView.backgroundColor     = [UIColor groupTableViewBackgroundColor];
    return headerTitleView;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 85;
    }
    if (indexPath.section == self.orderModel.prodsInfo.count + 2 -1) {
        return 44;
    }
    return 82;
}

#pragma mark - tableView datasource
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        OrderDetailNumCell * cell  = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([OrderDetailNumCell class]) forIndexPath:indexPath];
        cell.inputImage.hidden = YES;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.noPayLabel.text = _orderType;
        if ([_orderType isEqualToString:@"未付款"]) {
            cell.noPayLabel.textColor  = SBpurpleColor;
        }else{
            cell.noPayLabel.textColor = TabBarTitleColor;
        }
        return cell;
    }
    if (indexPath.section >0 && indexPath.section <self.orderModel.prodsInfo.count + 2-1) {
        OrderDetailImageCell * cell  = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([OrderDetailImageCell class]) forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        QZShopCarModel *model = self.orderModel.prodsInfo[indexPath.section - 1];
        cell.shopModel = model;
        return cell;
    }
    
    if(indexPath.section == self.orderModel.prodsInfo.count + 2 - 1){
        OrderDetailCommomTableViewCell * cell  = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([OrderDetailCommomTableViewCell class]) forIndexPath:indexPath];
        cell.inputImage.hidden = YES;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row == 0) {
            cell.titleLabel.text = @"商家优惠";
            cell.contentLabel.text = @"省20元，满100减20";
        }else if(indexPath.row == 1){
            cell.titleLabel.text = @"配送方式";
            cell.contentLabel.text = @"快递包邮";
        }else{
//            cell.titleLabel.text = @"共 0 件商品";
//            cell.contentLabel.text = @"合计 0 元";
        }
        return cell;
    }

    
    return nil;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.orderModel.prodsInfo.count + 2;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (section == self.orderModel.prodsInfo.count + 2 -1 ) {
        return 3;
    }else{
        return 1;
    }
}
-(void)actionAtIndexPath:(NSIndexPath *)indexPath
{

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)request_POST_FinishValue:(id)value tagNSString:(NSString *)tag{
    
    if ([tag isEqualToString:@"获取订单详情"]) {
        
        NSDictionary *dictionary = value[@"data"];
        if (!dictionary[@"status"]) {
            return;
        }
        
        NSDictionary *data = dictionary[@"data"];
        QZOrderModel *model = [[QZOrderModel alloc] initWithDictionary:data error:nil];
        self.orderModel = model;
        [self addDataToUI:model];
    }
    
    if ([tag isEqualToString:@"取消预约"]) {
        if ([value[@"data"][@"status"] integerValue] == 100) {
            [[iToast makeText:@"订单已取消"] show];
        }else{
            [[iToast makeText:@"订单已取消"] show];
        }
        [self.navigationController popViewControllerAnimated:YES];
    }

    if ([tag isEqualToString:@"确认收货"]) {
        
        if ([value[@"data"][@"status"] integerValue] == 100) {
            [self downloadDatas];
        }else{
            [[iToast makeText:@"网咯出错"] show];
        }
        
        
    }
    
    if ([tag isEqualToString:@"退款"]) {
        if ([value[@"data"][@"status"] integerValue] == 100) {
            [[iToast makeText:@"已申请退款"] show];
        }else{
            [[iToast makeText:value[@"data"][@"info"]] show];
        }
    }
    
    if ([tag isEqualToString:@"售后"]) {
        if ([value[@"data"][@"status"] integerValue] == 100) {
                [[[UIAlertView alloc] initWithTitle:@"提示" message:@"我们已收到,客服会尽快与您联系" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"确认", nil] show];
        }else{
             [[iToast makeText:value[@"data"][@"info"]] show];
        }
    }
}
-(void)addDataToUI:(QZOrderModel *)model{
    [self.tableView reloadData];
    _orderNoView.orderabel.text = model.order_num;
    _orderNoView.typeTitleLabel.text = [self starString:model.orderStatus];
    
    NSIndexPath *path1 = [NSIndexPath indexPathForRow:0 inSection:0];
    OrderDetailNumCell *cell = [self.tableView cellForRowAtIndexPath:path1];
    cell.name.text = model.addressInfo.receiver;//联系人
    cell.phone.text = model.addressInfo.tel;
    cell.address.text = [NSString stringWithFormat:@"%@%@",model.addressInfo.addressbie,model.addressInfo.address];
    
    NSIndexPath *path2 = [NSIndexPath indexPathForRow:2 inSection:model.prodsInfo.count + 2 -1];
    OrderDetailCommomTableViewCell *cell2 = [self.tableView cellForRowAtIndexPath:path2];
    cell2.titleLabel.text = [NSString stringWithFormat:@"共 %ld 件商品",model.amount];
    cell2.contentLabel.text = [NSString stringWithFormat:@"合计 %@ 元",model.price];
    
    [self createBottomView:model.orderStatus];
    
    [self.tableView reloadData];
}

/** 订单状态 */
-(NSString *)starString:(NSInteger)index{
    
    //@"待发货",@"待收货",@"交易成功",@"退款中",@"未付款"
    //  (0待付款(1待发货(2待收货(3售后
    NSString *string = nil;
    
    switch (index) {
        case 0:
            string = @"未付款";
            break;
        case 1:
            string = @"待发货";
            break;
        case 2:
            string = @"待收货";
            break;
        case 3:
            string = @"退款中";
            break;
        case 4:
            string = @"已退款";
            break;
        case 5:
            string = @"交易完成";
            break;
        case -1:
            string = @"已取消";
            break;
        default:
            break;
    }
    
    return string;
}
@end
